package com.mediacloud.app.newsmodule.activity

import android.content.Context
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.mediacloud.app.assembly.util.ConfiguRation
import com.mediacloud.app.assembly.util.Utility
import com.mediacloud.app.assembly.views.GlideRoundTransform
import com.mediacloud.app.model.activity.BaseBackActivity4NoDetail
import com.mediacloud.app.model.interfaces.DataInvokeCallBack
import com.mediacloud.app.model.news.BaseMessageReciver
import com.mediacloud.app.model.news.FollowDataReceiver
import com.mediacloud.app.model.news.FollowItem
import com.mediacloud.app.model.utils.DefaultBgUtil
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.utils.GetInterestInvoker
import com.mediacloud.app.newsmodule.utils.InterestInvoker
import com.mediacloud.app.user.model.UserInfo
import com.sbhandmark.pulltorefresh.library.PullToRefreshBase
import com.sbhandmark.pulltorefresh.library.PullToRefreshGridView

class FollowActivityX : BaseBackActivity4NoDetail() {
    private var mGridView: PullToRefreshGridView? = null
    private var mButton: TextView? = null
    private var mAdapter: FollowAdapter? = null
    private var getInterestInvoker: GetInterestInvoker? = null
    private var getCallBack: GetInterestCallBack? = null
    private var pullCallBack: PullInterestCallBack? = null
    private var pullInterestInvoker: InterestInvoker? = null
    private val perPage = 8
    private var page = 1
    private val haveMore = true

    override fun getLayoutResID(): Int {
        return R.layout.activity_follow
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initView()
        setInvoker()
        getInterestTagList()
        setListener()
    }

    private fun setInvoker() {
        getCallBack = GetInterestCallBack()
        getInterestInvoker = GetInterestInvoker(getCallBack)
        pullCallBack = PullInterestCallBack()
        pullInterestInvoker = InterestInvoker(pullCallBack)
    }

    private fun getInterestTagList() {
        getInterestInvoker!!.getInterestTagList(page, perPage)
    }

    private fun initView() {
        setTitle(R.string.interest)
        mGridView = Utility.findViewById(mRootView, R.id.follow_gridView)
        mButton = Utility.findViewById(mRootView, R.id.follow_sure)
        mAdapter = FollowAdapter(this)
        mGridView?.setAdapter(mAdapter)
        mGridView?.getRefreshableView()
        mGridView?.setMode(PullToRefreshBase.Mode.PULL_FROM_START)
    }


    private fun setListener() {
        mGridView!!.setOnRefreshListener {
            page = 1
            getInterestTagList()
        }
        mGridView!!.setOnLastItemVisibleListener(PullToRefreshBase.OnLastItemVisibleListener {
            if (!haveMore) return@OnLastItemVisibleListener
            page++
            getInterestTagList()
        })
        mGridView!!.setOnItemClickListener { parent, view, position, id ->
            val item = mAdapter!!.getItem(position) as FollowItem
            mAdapter!!.setSelected(item)
            if (mAdapter!!.getSelected().size > 0) {
                mButton!!.setBackgroundColor(DefaultBgUtil.getTintColor(this@FollowActivityX))
                mButton!!.text =
                    resources.getString(R.string.sure) + "（" + mAdapter!!.getSelected().size + "）"
            } else {
                mButton!!.setBackgroundColor(-0x1b1b1c)
                mButton!!.setText(R.string.sure)
            }
        }
        mButton!!.setOnClickListener { finish() }
    }

    override fun finish() {
        val mUser = UserInfo.getUserInfo(this)
        val config = ConfiguRation(this)
        config.shardBoolean("FOLLOW_" + mUser.userid, true)
        if (mAdapter!!.getSelected().size > 0) {
            var preference = ""
            for (item in mAdapter!!.getSelected()) {
                preference += item.tagName + ","
            }
            pullInterestInvoker!!.addInsterestTag(
                mUser.userid,
                preference.substring(0, preference.length - 1)
            )
        }
        super.finish()
    }

    /**
     * 提交兴趣 回调接口
     */
    internal class PullInterestCallBack : DataInvokeCallBack<BaseMessageReciver?> {
        override fun success(data: BaseMessageReciver?) {
            TODO("Not yet implemented")
        }

        override fun fault(data: Any) {}
    }

    /**
     * 获取兴趣列表 回调接口
     */
    internal class GetInterestCallBack : DataInvokeCallBack<FollowDataReceiver?> {


        override fun success(data: FollowDataReceiver?) {

        }

        override fun fault(data: Any) {
        }
    }


    internal class FollowAdapter(private val mContext: Context) : BaseAdapter() {
        private val items: MutableList<FollowItem>
        private val selected: MutableList<FollowItem>

        init {
            items = ArrayList()
            selected = ArrayList()
        }

        fun setItems(items: List<FollowItem>?) {
            this.items.clear()
            selected.clear()
            this.items.addAll(items!!)
            notifyDataSetChanged()
        }

        fun addItems(items: List<FollowItem>?) {
            this.items.addAll(items!!)
            notifyDataSetChanged()
        }

        fun setSelected(item: FollowItem) {
            if (selected.contains(item)) {
                selected.remove(item)
            } else {
                selected.add(item)
            }
            notifyDataSetChanged()
        }

        fun getSelected(): List<FollowItem> {
            return selected
        }

        override fun getCount(): Int {
            return if (items.size > 0) items.size else 0
        }

        override fun getItem(position: Int): Any {
            return items[position]
        }

        override fun getItemId(position: Int): Long {
            return position.toLong()
        }

        override fun getView(position: Int, convertView: View, parent: ViewGroup): View {
            var convertView = convertView
            var holder: ViewHolder? = null
            if (convertView == null) {
                holder = ViewHolder()
                convertView = View.inflate(mContext, R.layout.follow_item, null)
                holder!!.mSelectedView = convertView.findViewById(R.id.follow_item_selected)
                holder.tagImage = convertView.findViewById(R.id.follow_item_img)
                holder.tagName = convertView.findViewById(R.id.follow_item_title)
                convertView.tag = holder
            } else {
                holder = convertView.tag as ViewHolder
            }
            val params = holder!!.tagImage!!.layoutParams as RelativeLayout.LayoutParams
            params.width = 1
            params.height = params.width
            holder.tagImage!!.layoutParams = params
            holder.mSelectedView!!.layoutParams = params
            val item = items[position]
            val myOptions = RequestOptions()
                .centerCrop()
                .transform(
                    GlideRoundTransform(
                        mContext, Utility.dpToPx(
                            mContext, 1.6875f
                        ).toFloat()
                    )
                )
            Glide.with(mContext)
                .load(item.tagImage)
                .into(holder.tagImage!!)
            holder.tagName!!.text = item.tagName
            if (selected.contains(item)) {
                holder.mSelectedView!!.visibility = View.VISIBLE
            } else {
                holder.mSelectedView!!.visibility = View.GONE
            }
            return convertView
        }

        internal inner class ViewHolder {
            var mSelectedView: View? = null
            var tagImage: ImageView? = null
            var tagName: TextView? = null
        }
    }
}